package com.example.backend.controller;

import com.example.backend.entity.User;
import com.example.backend.model.BaseModel;
import com.example.backend.model.LoginModel;
import com.example.backend.service.AdminService;
import com.example.backend.service.UserService;
import com.example.backend.utils.JWTTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private AdminService adminService;

    @Resource
    HttpSession session;

    @Resource
    HttpServletRequest request;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public BaseModel userLogin() {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        //区分管理员和用户，0为用户，1为管理员
        String authority = request.getParameter("authority");
        if (Integer.parseInt(authority) == 0) {
            //用户登录
            if (userService.userLogin(userName, password)) {
                String token=JWTTokenUtil.token(userName,password);
                return new LoginModel(0, "success",token);
            }
            return new BaseModel(1, "error");
        }
        else {
            //管理员登录
            if (adminService.adminLogin(userName, password)) {
                String token=JWTTokenUtil.token(userName,password);
                return new LoginModel(0, "success",token);
            } else
                return new BaseModel(1, "error");
        }
    }

    @RequestMapping(value = "insertUser",method = RequestMethod.POST)
    public BaseModel insertUser(){
        int userId = Integer.parseInt(request.getParameter("userId"));
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        int sex = Integer.parseInt(request.getParameter("sex"));
        int age = Integer.parseInt(request.getParameter("age"));
        String phone = request.getParameter("phone");
        if(userService.insertUser(userId,userName,password,sex,age,phone))
            return new BaseModel(0,"success");
        else
            return new BaseModel(1,"error");
    }
}